package com.ohuang.baseapp.dialog;


import com.ohuang.baseapp.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.FrameAnimationElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;


public class LoadingDialog extends CommonDialog {

    private MyViewHolder mViewHolder;

    private Context mContext;

    private FrameAnimationElement frameAnimationElement;

    public LoadingDialog(Context context) {
        super(context);
        mContext = context;

        initComponent();
    }

    void initComponent(){
        Component layout = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_refresh_loading_view, null, true);
        //设置位置
        setAlignment(LayoutAlignment.CENTER);
        // 设置布局
        setContentCustomComponent(layout);
        // 设置背景透明
        setTransparent(true);
        mViewHolder = new MyViewHolder(layout);

        init();
    }

    private void init() {
        frameAnimationElement = new FrameAnimationElement(mContext, ResourceTable.Graphic_animation_element_loading_dialog);
        mViewHolder.mComponent.setBackground(frameAnimationElement);

    }

    public LoadingDialog setText(String text){
        mViewHolder.mText.setText(text);
        return this;
    }




    public LoadingDialog setFrameAnimationElementID(int id){
        frameAnimationElement = new FrameAnimationElement(mContext, id);
        mViewHolder.mComponent.setBackground(frameAnimationElement);
        return this;
    }



    @Override
    public void show() {
        super.show();
        setStartRefresh();
    }


    @Override
    public void hide() {
        super.hide();
        setFinishRefresh();
    }

    @Override
    public void destroy() {
        setFinishRefresh();
        super.destroy();
    }

    private void setStartRefresh() {
        if (mViewHolder != null) {
            frameAnimationElement.start();
        }
    }

    private void setStopRefresh() {
        frameAnimationElement.stop();

    }

    private void setFinishRefresh() {
        frameAnimationElement.stop();
        frameAnimationElement.release();
    }


     static class MyViewHolder {
        Component mComponent;
        Text mText;

         MyViewHolder(Component v) {
            mComponent = (Component) v.findComponentById(ResourceTable.Id_component);
            mText = (Text) v.findComponentById(ResourceTable.Id_text);
        }
    }
}
